<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <div style="text-align: center;">
          <h3>管理系统</h3>
        </div>
        <el-menu :default-active="activeMenu" @select="handleMenuSelect">
          <el-menu-item index="user-management">用户管理</el-menu-item>
          <el-menu-item index="task-management">任务管理</el-menu-item>
          <el-menu-item index="record-management">记录管理</el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header style="display: flex; justify-content: flex-end; align-items: center;">
          <el-avatar src="../assets/user.jpg" size="medium"/>
          <span style="margin-left: 10px;">用户名</span>
          <el-button type="text" @click="handleLogout" style="margin-left: 10px;">退出</el-button>
        </el-header>
        <el-main>
          <component :is="currentComponent"></component>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {ref, computed} from 'vue';
import {ElMessage} from 'element-plus';
import {useRouter} from 'vue-router';

const router = useRouter();

// 定义激活的菜单项
const activeMenu = ref('user-management');

// 导入子组件
import UserManagement from '../components/UserManagement.vue';
import TaskManagement from '../components/TaskManagement.vue';
import RecordManagement from '../components/RecordManagement.vue';
import {userLogout} from "@/api";

// 菜单项与组件的映射关系
const componentsMap = {
  'user-management': UserManagement,
  'task-management': TaskManagement,
  'record-management': RecordManagement,
};

// 当前显示的组件
const currentComponent = computed(() => componentsMap[activeMenu.value]);

// 菜单选择事件处理
const handleMenuSelect = (index) => {
  activeMenu.value = index;
};

// 处理退出登录
const handleLogout = async () => {
  const response = await userLogout();
  if (response.data.success === true) {
    //注销登录
    ElMessage.success('注销成功');
  } else {
    ElMessage.error(response.data.errorMessage);
  }

  // 清除 token 或其他用户信息
  localStorage.removeItem('token');

  // 跳转到登录页面
  await router.push('/login')
};
</script>

<style scoped>
/* 自定义样式 */
.el-header {
  background-color: #f5f5f5;
  padding: 0 20px;
}
</style>
